package com.ccys.cms.controller.corporateAndInsurance;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.ccys.cms.service.corporateAndInsurance.PlanBenefitIdentifierService;
import com.ccys.cms.service.corporateAndInsurance.PlanBenefitMemberService;
import com.ccys.common.util.easyExcel.EasyExcelUtil;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.corporateAndInsurance.PlanBenefitMemberDto;
import com.ccys.db.entity.TblPlanBenefitIdentifier;
import com.ccys.db.entity.TblPlanBenefitMember;
import com.ccys.db.mapper.TblPlanBenefitIdentifierMapper;
import com.ccys.db.vo.corporateAndInsurance.ImportMemberTempVo;
import com.ccys.db.vo.corporateAndInsurance.ImportMemberVo;
import com.ccys.db.vo.corporateAndInsurance.PlanBenefitIdentifierExcelVo;
import com.ccys.db.vo.corporateAndInsurance.PlanBenefitMemberVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/corporateAndInsurance")
@Api(tags = "配套会员管理")
@Slf4j
public class PlanBenefitMemberController {


    @Resource
    private PlanBenefitIdentifierService identifierService;

    @Resource
    private TblPlanBenefitIdentifierMapper identifierMapper;

    @Resource
    private PlanBenefitMemberService memberService;


    @Resource
    private PlanBenefitMemberService service;

    @PutMapping("planBenefitMember")
    @ApiOperation("修改状态")
    @Transactional
    public ResponseResult saveOrUpdate(TblPlanBenefitMember model) {
        int i = service.insertOrUpdate(model);
        return ResponseResult.update(i);
    }


    @GetMapping("planBenefitMember")
    @ApiOperation(value = "在benefit里面查询member分页")
    public ResponseResult<PageInfo<PlanBenefitMemberVo>, Object> getPage(PlanBenefitMemberDto dto) {
        return service.getPage(dto);
    }


    @PostMapping("saveBatchIdentifier")
    @ApiOperation("direct coporate 添加 identifier")
    @Transactional
    public ResponseResult saveBatchIdentifier(List<TblPlanBenefitIdentifier> identifierList) {

        identifierList.forEach(x -> {
            x.setId(IdUtil.getSnowflakeNextIdStr());
            if (StringUtils.isEmpty(x.getIdentifier())) {
                //生成identifier 随机6个字符
                x.setIdentifier(RandomUtil.randomString(6));
            }
        });
        int i = identifierService.insertAll(identifierList);
        return ResponseResult.update(i);
    }


    @ApiOperation("导出csv")
    @GetMapping("exportMember")
    public ResponseResult exportMember(PlanBenefitMemberDto dto, HttpServletResponse response) {
        List<PlanBenefitIdentifierExcelVo> exportList = identifierMapper.getExportList(dto);
        long timeMillis = System.currentTimeMillis();
        EasyExcelUtil.export(response, exportList, PlanBenefitIdentifierExcelVo.class, timeMillis + "");
        return ResponseResult.success();
    }


    @ApiOperation("导入csv")
    @PostMapping("importMember")
    public ResponseResult importMember(MultipartFile file) {

        CompletableFuture.runAsync(() -> {
            try {
                EasyExcel.read(file.getInputStream(), ImportMemberTempVo.class, new ReadListener<ImportMemberTempVo>() {
                    /**
                     * 单次缓存的数据量
                     */
                    public static final int BATCH_COUNT = 100;
                    /**
                     *临时存储
                     */
                    private List<ImportMemberTempVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

                    @Override
                    public void invoke(ImportMemberTempVo data, AnalysisContext context) {
                        cachedDataList.add(data);
                        if (cachedDataList.size() >= BATCH_COUNT) {
                            saveData();
                            // 存储完成清理 list
                            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                        }
                    }


                    @Override
                    public void doAfterAllAnalysed(AnalysisContext context) {
                        saveData();
                    }

                    /**
                     * 加上存储数据库
                     */
                    private void saveData() {
                        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
                        List<String> memCodeList = cachedDataList.stream().map(ImportMemberTempVo::getMemberCode).collect(Collectors.toList());
                        //查询所有code相关的memId
                        List<ImportMemberVo> idByCodeList = identifierMapper.getMemberIdByCodeList(memCodeList);
                        if (CollectionUtils.isNotEmpty(idByCodeList) && CollectionUtils.isNotEmpty(cachedDataList)) {
                            Map<String, String> idMap = idByCodeList.stream().collect(Collectors.toMap(ImportMemberVo::getCode, ImportMemberVo::getId));
                            List<TblPlanBenefitMember> memberList = new ArrayList<>();
                            for (int i = 0; i < cachedDataList.size(); i++) {
                                ImportMemberTempVo cache = cachedDataList.get(i);
                                String memberCode = cache.getMemberCode();
                                String idValue = idMap.get(memberCode);
                                if (StringUtils.isNotEmpty(idValue)) {
                                    TblPlanBenefitMember member = new TblPlanBenefitMember();
                                    BeanUtils.copyProperties(cache, member);
                                    member.setMemId(idValue);
                                    member.setId(IdUtil.getSnowflakeNextIdStr());
                                    memberList.add(member);
                                }
                            }
                            if (CollectionUtils.isNotEmpty(memberList)) {
                                memberService.insertAll(memberList);
                            }
                        }
                        log.info("存储数据库成功！");
                    }
                }).sheet().doRead();
            } catch (IOException e) {
                log.error("导入失败:,{}", e);
            }
        });


        return ResponseResult.success();
    }


}
